package com.etv.launcher.ui.component.status;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.os.Looper;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextClock;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class TimeComponent extends BaseStatusBarComponent {
    private TextClock textClock;
    private TextView tvLunarWeek;
    private TextView tvSolar;
    private Handler handler;
    private Runnable minuteCallback;

    public TimeComponent(Context context) {
        super(context);
    }

    @Override
    public void initView(Context context) {
        // 创建根容器（横向线性布局）
        LinearLayout rootLayout = new LinearLayout(context);
        rootLayout.setOrientation(LinearLayout.HORIZONTAL);
        rootLayout.setPadding(dpToPx(8), 0, dpToPx(8), 0);
        rootLayout.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));

        // 左侧时间区域（TextClock）
        textClock = new TextClock(context);
        textClock.setFormat24Hour("HH:mm");
        textClock.setFormat12Hour("HH:mm");
        textClock.setTextSize(TypedValue.COMPLEX_UNIT_SP, 36);
        textClock.setTextColor(0xFF333333);
        LinearLayout.LayoutParams timeParams = new LinearLayout.LayoutParams(
                dpToPx(80),  // 固定宽度
                ViewGroup.LayoutParams.MATCH_PARENT
        );
        textClock.setLayoutParams(timeParams);

        // 右侧信息容器（纵向布局）
        LinearLayout rightLayout = new LinearLayout(context);
        rightLayout.setOrientation(LinearLayout.VERTICAL);
        rightLayout.setGravity(Gravity.CENTER_VERTICAL);
        LinearLayout.LayoutParams rightParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        );
        rightParams.setMargins(dpToPx(12), 0, 0, 0);
        rightLayout.setLayoutParams(rightParams);

        // 农历+星期
        tvLunarWeek = new TextView(context);
        tvLunarWeek.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        tvLunarWeek.setTextColor(0xFF333333);

        // 阳历日期
        tvSolar = new TextView(context);
        tvSolar.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        tvSolar.setTextColor(0xFF333333);

        // 组装视图
        rightLayout.addView(tvLunarWeek);
        rightLayout.addView(tvSolar);
        rootLayout.addView(textClock);
        rootLayout.addView(rightLayout);
        this.rootView = rootLayout;


        // 初始化时间同步
        initTimeUpdates();
    }

    @Override
    public void setOnComponentClickListener(View.OnClickListener listener) {

    }

    private void initTimeUpdates() {
        handler = new Handler(Looper.getMainLooper());

        // 首次立即更新数据
        updateLunarAndSolar();

        // 计算到下一个整分钟的延迟
        long currentMillis = System.currentTimeMillis();
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(currentMillis);
        int seconds = cal.get(Calendar.SECOND);
        long delay = (60 - seconds) * 1000;

        minuteCallback = new Runnable() {
            @Override
            public void run() {
                updateLunarAndSolar();
                handler.postDelayed(this, 60_000); // 后续每分钟触发
            }
        };
        handler.postDelayed(minuteCallback, delay);
    }

    @Override
    protected void updateSelectionUI(boolean selected) {
        // 创建圆角背景（支持 API 21+ 的优化写法）
        GradientDrawable bg = new GradientDrawable();
        bg.setShape(GradientDrawable.RECTANGLE);
        bg.setCornerRadius(dpToPx(6));
        bg.setColor(selected ? 0x33CCCCCC : Color.TRANSPARENT);
        rootView.setBackground(bg);
    }

    // 清理资源（防止内存泄漏）
    public void onDestroy() {
        if (handler != null && minuteCallback != null) {
            handler.removeCallbacks(minuteCallback);
        }
    }

    private void updateLunarAndSolar() {
        // 这里实现实际数据获取逻辑，以下是示例数据
        String lunar = getLunarDate();  // 示例："二月初二"
        String week = getWeek();        // 示例："周五"
        String solar = getSolarDate();  // 示例："2024年3月21日"

        tvLunarWeek.setText(String.format("%s · %s", lunar, week));
        tvSolar.setText(solar);
    }

    // 以下为模拟方法，需替换为真实数据源
    private String getLunarDate() {
        return "二月初二";
    }

    private String getWeek() {
        SimpleDateFormat sdf = new SimpleDateFormat("EE", Locale.CHINA);
        return sdf.format(new Date());
    }

    private String getSolarDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINA);
        return sdf.format(new Date());
    }

    private int dpToPx(int dp) {
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                dp,
                rootView.getResources().getDisplayMetrics()
        );
    }
}
